﻿using Code.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Code.Repsitory
{
    public class BaseRepository<TEntity> : IBaseRepository<TEntity>
        where TEntity : class
    {
        protected CodeAPPContext db;

        public int Delete(int id)
        {
            var entity = db.Set<TEntity>().Find(id);
            db.Set<TEntity>().Remove(entity);
            return db.SaveChanges();
        }

        public int Delete(int[] idList)
        {
            foreach (var item in idList)
            {
                var entity = db.Set<TEntity>().Find(item);
                db.Set<TEntity>().Remove(entity);
            }
            
            return db.SaveChanges();
        }

        public int Delete(TEntity entity)
        {            
            db.Entry<TEntity>(entity).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
            return db.SaveChanges();
        }

        public int Delete(List<TEntity> entity)
        {
            db.Set<TEntity>().RemoveRange(entity);
            return db.SaveChanges();
        }

        public int Delete(Expression<Func<TEntity, bool>> condition)
        {
            var list = db.Set<TEntity>().Where(condition).ToList();
            db.Set<TEntity>().RemoveRange(list);
            return db.SaveChanges();
        }

        public virtual TEntity Insert(TEntity eneity)
        {
            db.Set<TEntity>().Add(eneity);
            db.SaveChanges();
            return eneity;
        }

        public virtual IQueryable<TEntity> Queryable()
        {
            return db.Set<TEntity>();
        }

        public List<TEntity> QueryAll()
        {
            return db.Set<TEntity>().ToList();
        }

        public List<TEntity> Query(Expression<Func<TEntity, bool>> condition)
        {
            return db.Set<TEntity>().Where(condition).ToList();
        }

        public TEntity QueryFirst(int id)
        {
            return db.Set<TEntity>().Find(id);
        }

        public TEntity Update(TEntity entity)
        {
            db.Set<TEntity>().Update(entity);
            return entity;
        }
    }
}
